import urllib.request as ur
import urllib.parse as up
import json
import time

while True:
    content = input('请输入翻译内容：(输入"q!"退出程序)')
    if content == 'q!': 
        break
    
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
##隐藏User-Agent实现防止爬虫检测
    head = {}
    head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'

    data = {}
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = '15958358858359'
    data['sign'] = '4d63de5ae6f2c946e7356a67a97820db'
    data['ts'] = '1595835885835'
    data['bv'] = '44a53b4124e8b822ebfd881c5a599938'
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] ='fanyi.web'
    data['action'] ='FY_BY_REALTlME'
    data = up.urlencode(data).encode('utf-8')

    response = ur.urlopen(url, data)
    html = response.read().decode('utf-8')

    target = json.loads(html)
    print("翻译结果:%s" % (target['translateResult'][0][0]['tgt']))

##    print(target)
    time.sleep(5)
